package com.young.dubbo.register;

import com.young.dubbo.framework.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口注册中心
 */
public class RemoteMapRegister {
    /**
     * 存放所有已经注册过的接口以及url地址
     */
    private static Map<String, List<URL>> REGISTER = new HashMap<>();

    /**
     * 注册接口服务
     * @param interfaceName
     * @param url
     */
    public static void register(String interfaceName,URL url){
        List<URL> urls = REGISTER.get(interfaceName);
        if (urls==null){
            urls = new ArrayList<>();
        }
        urls.add(url);
        REGISTER.put(interfaceName,urls);
        saveFile();
    }

    /**
     * 将已经注册的接口序列化到本地文件放置丢失
     */
    private static void saveFile(){
        try (FileOutputStream fileOutputStream = new FileOutputStream("/temp.txt")) {
            ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
            oos.writeObject(REGISTER);
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据接口名称获取已经注册的url地址
     * @param interfaceName
     * @return
     */
    public static List<URL> get(String interfaceName){
        REGISTER = getFile();
        List<URL> urls = REGISTER.get(interfaceName);
        return urls;
    }

    /**
     * 从文件反序列化出已经注册到的接口信息
     * @return
     */
    private static Map<String, List<URL>> getFile() {
        try (FileInputStream fileInputStream = new FileInputStream("/temp.txt")) {
            ObjectInputStream ois = new ObjectInputStream(fileInputStream);
            return (Map<String, List<URL>>) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;

    }
}
